const { exec } = require('child_process')
const { resolve } = require('path')
const fs = require('fs')

// 截屏
function screenshot ({ videoPath, outputPath, time, isAfterPath, isJoinPath, isJoinFile }) {
  let filename = 'image-%3d.jpg'
  let vname = (/[\/\\]?([^\/\\]+?)\.([^\/\\]+?)$/.exec(videoPath) || [])[1] || ''
  vname = vname.replace(/#|%|&|\*|\||\\|\/|:|"|'|<|>|\?|`|~|\.|\(|\)|\s+/g, '')
  if (isAfterPath) {
    outputPath = outputPath + '/' + vname
  } else if (isJoinPath) {
    outputPath = outputPath + '-' + vname
  } else if (isJoinFile) {
    filename = vname + '-' + filename
  }
  buildPath(outputPath)
  const ffmpegCommand = 'ffmpeg -i ' + videoPath + ' -f image2  -q:v 2 -vf fps=fps=1/' + time + ' ' + outputPath + '/' + filename
  exec(ffmpegCommand, (error, stdout, stderr) => {
    if (error) {
      console.error(`执行的错误: ${error}`)
      return
    }
    console.log('Screenshot Done !')
    // console.log(`stdout: ${stdout}`)
    // console.error(`stderr: ${stderr}`)
  })
}

function buildPath (folderpath) {
  if (typeof folderpath !== 'string') {
    return false
  }
  folderpath = resolve(folderpath).replace(/\\/g, '/')
  const pathArr = folderpath.split('/')
  let _path = ''
  for (let i = 0; i < pathArr.length; i++) {
    // 盘符
    if (!i && /\w+:/.test(pathArr[i])) {
      _path += pathArr[i]
    }
    else if (pathArr[i]) {
      _path += `/${pathArr[i]}`
      if (!fs.existsSync(_path)) {
        fs.mkdirSync(_path)
      }
    }
  }
}

// 每0.5s截取一次图片
// screenshot({
//   videoPath: './video/demo.mp4',
//   outputPath: './media/screenshot',
//   time: 0.5
// })

screenshot({
  videoPath: 'E:/workspace/documents/202410/归档/B3A793/B3A793.mp4',
  outputPath: 'E:/workspace/documents/202410/归档/B3A793/screenshot',
  time: 0.1,
  isJoinPath: true
})
